#!/opt/lampp/bin/php
<?php
    require_once 'core/config.php';
    require_once 'core/file_helper.php';
    require_once 'core/cr_helper.php';
    require_once 'core/loader.php';
    require_once 'core/db.php';
    require_once 'entities/crash_report.php';
    $model = load_model("crash_model");
    if ($argc < 3) {
        print "usage -- $argv[0] [archive file] [reporter] [create_time] \n";
        exit(1);
    }
    $reporter = $argv[2];
    $create_time = isset($argv[3])?$argv[3]:"CURRENT_TIMESTAMP";
    $arc_file_path = get_file_abs_path($argv[1]);
    $arc_file_name = basename($arc_file_path);
    if (!file_exists($arc_file_path)) {
        echo "arc file passed not exist";
        exit(0);
    }
    if (!file_exists(WORK_PATH)) {
        mkdir(WORK_PATH);
    }
    $work_path = path_join(WORK_PATH, substr($arc_file_name,0, strrpos($arc_file_name, '.')));
    if (!file_exists($work_path)) {
        mkdir($work_path);
    }
    chdir($work_path);

    // $db->where('id', 1);
    // $db->select(array('id', 'name'));
    // $resutl = $db->get('crash_reports');
    
    extract_file($arc_file_path, "./");
    $crash_reports = parse_crash_report("CrashReport.txt");
    if ($crash_reports == NULL) {
        echo "No crash report find!\n";
        exit(1);
    }
    foreach ($crash_reports as $crash) {
        $crash->build_backtrace();
        $crash->reporter = $reporter;
        $crash->crash_report_path = $arc_file_path;
        $crash->upload_time = $create_time;
        $similar_id = 0;
        if ($crash->process_type == 0) {
            $similar_id = $model->get_similar_crash($crash);
        } else {
            $similar_id = $model->get_similar_crash($crash, 99);
        }
        if ( $similar_id == 0) {
            dbg("insert!");
            $model->insert_crash_report($crash);
        } else {
            dbg("update");
            $model->increase(array('id'=>$similar_id), array('repeat'));
            $model->update(array('id'=>$similar_id), array('upload_time'=>$create_time));
        }
    }
?>
